package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.entity.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.entity.BaseAttrInfo;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author weiranyi
 * @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
 * @createDate 2022-11-29 16:41:28
 */
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
        implements BaseAttrInfoService {
    @Autowired
    BaseAttrValueService baseAttrValueService;

    @Override
    public List<BaseAttrInfo> getBaseAttrAndValue(Long category1Id, Long category2Id, Long category3Id) {
        return baseMapper.getBaseAttrAndValue(category1Id, category2Id, category3Id);
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1.属性名信息保存到base_attr_info
        boolean save = this.save(baseAttrInfo);
        //-得到自增id
        Long id = baseAttrInfo.getId();
        //2.属性值保存到base_attr_valve
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueService.save(baseAttrValue);
        }
    }

    @Override
    public void updateAttrInfo(BaseAttrInfo baseAttrInfo) {
        // 1.修改属性表
        this.updateById(baseAttrInfo);
        // 2.修改值表
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        // 前端没有id的是新增
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if (baseAttrValue.getId() == null) {
                // 回填attrId
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueService.save(baseAttrValue);
            } else {
                // 前端提交带了id是修改
                baseAttrValueService.updateById(baseAttrValue);
            }
        }
        // 前端没提交的是删除 not in
        ArrayList<Long> ids = new ArrayList<>();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if (baseAttrValue.getId() != null) {
                ids.add(baseAttrValue.getId());
            }
        }
        LambdaUpdateChainWrapper<BaseAttrValue> wrapper = baseAttrValueService.lambdaUpdate().eq(BaseAttrValue::getAttrId, baseAttrInfo.getId());
        if (ids.size() > 0) {
            wrapper.notIn(BaseAttrValue::getId, ids)
                    .remove();
        } else {
            wrapper.remove();
        }
    }
}




